package com.canace.novel.manager.mq;

import com.canace.novel.core.constant.AmqpConsts;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * @author canace
 * @version 1.0
 * @description AMQP 消息管理器
 * @date 2024/2/23 10:32
 */


@Component
@RequiredArgsConstructor
public class AmqpMsgManager {

    private final AmqpTemplate amqpTemplate;

    @Value("${spring.amqp.enabled:false}")
    private boolean amqpEnabled;

    // 在小说进行信息更新或者新建时，只需调用这个接口即可实现
    // 这里没有写更新书籍信息的接口，不做演示
    // amqpMsgManager.sendBookChangeMsg(dto.getBookId());
    public void sendBookChangeMsg(Long bookId){
        if (amqpEnabled) {
            sendAmqpMessage(amqpTemplate, bookId);
        }
    }

    private void sendAmqpMessage(AmqpTemplate amqpTemplate, Object message) {

        // 如果在事务中则在事务执行完成后再发送，否则可以直接发送
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(
                    new TransactionSynchronization() {
                        @Override
                        public void afterCommit() {
                            amqpTemplate.convertAndSend(AmqpConsts.BookChangeMQ.EXCHANGE_NAME, null, message);
                        }
                    });
            return;
        }
        // 将Java对象转为Amqp,并发送消息
        amqpTemplate.convertAndSend(AmqpConsts.BookChangeMQ.EXCHANGE_NAME, null, message);
    }


}
